package com.tosit.driverschool.controller;

import com.tosit.driverschool.common.entity.Vehicle;
import com.tosit.driverschool.service.VehicleService;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.ModelMap;

import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Set;

@Controller
@RequestMapping("/vehicle")
public class VehicleController {
    @Autowired
    VehicleService vehicleService;

    @GetMapping("/getall")
    public String list(ModelMap modelMap){
        List<Vehicle> all = vehicleService.findAll();
        modelMap.put("vehicles", all);
        modelMap.put("content", "vehicle-list");
        return "index";
    }
    @GetMapping("/selectbyid")
    @ResponseBody
    public JSONObject CeShi(@RequestParam("id") short id) {
        System.out.println("进入");
        JSONObject jsonObject = new JSONObject();
        Vehicle vehicle = this.vehicleService.selectbyId(id);
        if(vehicle!=null) {
            jsonObject.put("setId", vehicle.getSetId());
            jsonObject.put("subjectId", vehicle.getSubjectId());
            jsonObject.put("titleType", vehicle.getTitleType());
            jsonObject.put("vehicleName", vehicle.getVehicleName());
            jsonObject.put("vehicleType", vehicle.getVehicleType());
        }

        return jsonObject;
    }
    /*得到所有最大id*/
    @GetMapping("/getmaxId")
    @ResponseBody
    public JSONObject getmaxId() {
        System.out.println("进入");
        JSONObject jsonObject = new JSONObject();
        short a= this.vehicleService.getmaxId();
        jsonObject.put("setId", a+1);
        return jsonObject;
    }
    @Transactional
    @GetMapping("/delete/{id}")
    public String deleteByid(@PathVariable("id") short id,ModelMap modelMap){
        System.out.println(id);
        Vehicle vehicle = vehicleService.selectbyId(id);
        vehicle.setIsdelet(false);
        vehicleService.updateIsdelete(vehicle);

        return "redirect:/vehicle/getall";
    }
    @Transactional
    /*修改使用put方法*/
    @PutMapping("/update")
    public String update(ModelMap modelMap,Vehicle vehicle){
        System.out.println(vehicle.toString());
        vehicleService.update(vehicle);
        return "redirect:/vehicle/getall";
    }
    @Transactional
    /*修改使用put方法*/
    @PutMapping("/add")
    public String add(ModelMap modelMap,Vehicle vehicle){
        vehicle.setIsdelet(true);
        System.out.println(vehicle.toString());
        vehicleService.add(vehicle);
        return "redirect:/vehicle/getall";
    }

    @ResponseBody
    @GetMapping("/subject")
    public Object allType(String type ){
        Set<String> allSubject = vehicleService.getAllSubject(type);
        return allSubject;
    }
}
